/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.chain.presenter;

import br.com.model.Token;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextScrollPane;
import br.com.view.TelaPrincipalView;
import java.awt.Color;
import java.awt.ScrollPane;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.tree.DefaultTreeModel;

/**
 *
 * @author Bush
 */
public class TelaPrincipalPresenter {

    private TelaPrincipalView view;
    private static TelaPrincipalView viewStatic;
    private RSyntaxTextArea textArea;
    private AnalisadorLexico analizadorLexico;
    private AnalisadorSintatico analizadorSintatico;
    private ArrayList<String> erros;
    private ArrayList<Integer> nos;
    private int posicao;
    private DefaultTableModel tabelaDeSimbolos;
    private DefaultTableModel tabelaDeSaida;

    public TelaPrincipalPresenter() {
        view = new TelaPrincipalView();
        viewStatic = view;
        textArea = new RSyntaxTextArea(671, 455);
        AnalisadorLexico.getInstancia().setJTextArea(textArea);
        analizadorLexico = AnalisadorLexico.getInstancia();
        analizadorSintatico = new AnalisadorSintatico(analizadorLexico.getTabelaDeSibolos());     
        
        textArea.addKeyListener(new KeyAdapter() {

            @Override
            public void keyReleased(KeyEvent e) {
                int tecla = e.getKeyCode();
                if (tecla != 37 && tecla != 38 && tecla != 39 && tecla != 40) {
                    analizadorLexico.analiseLexica();
                    erros = analizadorSintatico.analiseSintatica(analizadorLexico.getTabelaDeSibolos());                    
                    analizadorTabelaSimbolo();
                    outputErrosSintaticos(erros);
                }
            }
        });

        textArea.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                posicaoMouse();
            }
        });

        view.getBtnAvancar().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.redoLastAction();
            }
        });

        view.getBtnVoltar().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.undoLastAction();
            }
        });

        view.getBtnBarraAvancar().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.redoLastAction();
            }
        });

        view.getBtnBarraVoltar().addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                textArea.undoLastAction();
            }
        });

        setTextArea();
        view.setLocationRelativeTo(view);
        view.setExtendedState(JFrame.MAXIMIZED_BOTH);
        view.setVisible(true);
    }

    public void analizadorTabelaSimbolo() {
        ArrayList<Token> tabelaSimbolos = analizadorLexico.getTabelaDeSibolos();
        definirTabelaSimbolos();
        definirTabelaSaida();
        if (tabelaSimbolos.size() > 0) {
            for (int i = 0; i < tabelaSimbolos.size(); i++) {
                String t = tabelaSimbolos.get(i).getLinha() + "@"
                        + tabelaSimbolos.get(i).getId() + "@"
                        + tabelaSimbolos.get(i).getLexema() + "@"
                        + tabelaSimbolos.get(i).getToken();
                String row[] = t.split("@");
                carregaTabelaDeSimbolos(row);
                outputErrosLexicos(tabelaSimbolos.get(i));

            }
        }
        //Possivel chamada de para exibir erros sintaticos
    }

    public void outputErrosLexicos(Token token) {
        String verificacao[] = token.getToken().split(":");
        if (verificacao[0].trim().equals("Erro")) {
            verificacao[0] = verificacao[1];
            verificacao[1] = String.valueOf(token.getLinha());
            carregaTabelaSaida(verificacao);
        }
    }

    public void outputErrosSintaticos(ArrayList<String> erros) {
        if (erros.size() >= 0) {
            for (int i = 0; i < erros.size(); i++) {
                String verificacao[] = erros.get(i).substring(5).split(":");                
                carregaTabelaSaida(verificacao);
            }
        }
    }

    public void setTextArea() {
        JPanel cp = new JPanel(new BorderLayout());

        textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_DELPHI);
        textArea.setCodeFoldingEnabled(true);
        textArea.setAutoIndentEnabled(true);
        textArea.setAntiAliasingEnabled(true);
        textArea.setHighlightCurrentLine(true);
        textArea.setLineWrap(true);
        RTextScrollPane sp = new RTextScrollPane(textArea);
        
        sp.setFoldIndicatorEnabled(true);
        sp.setVisible(true);
        cp.add(sp);
        //view.getjScrollPaneCodigo().setColumnHeaderView(textArea);
        view.getjScrollPaneCodigo().setColumnHeaderView(cp);
    }

    public void posicaoMouse() {
        int linha = textArea.getCaretLineNumber();
        linha++;
        view.getTxtLinhaPos().setText("Linha: " + linha);
    }

    public void carregaTabelaDeSimbolos(String[] texto) {
        this.tabelaDeSimbolos.addRow(texto);
    }

    public void carregaTabelaSaida(String[] texto) {
        this.tabelaDeSaida.addRow(texto);
    }

    //------------------------------------------ Arvore de Simbolos -----------------------------------------
    public void setArvoreSimbolos(DefaultTreeModel model) {
        view.getJTreeArvore().setModel(model);
    }

    // ---------------------------- Criação e definição de formato das Tabelas  ------------------------------
    public final void definirTabelaSaida() {
        JTable tabela = this.view.getjTableSaida();
        this.tabelaDeSaida = new DefaultTableModel(
                new Object[][]{},
                new String[]{"Analizador", "Linha"}) {

                    @Override
                    public boolean isCellEditable(int row, int col) {
                        return false;
                    }
                };
        tabelaDeSaida.setNumRows(0);
        tabela.setModel(tabelaDeSaida);
        tabela.getColumnModel().getColumn(1).setMaxWidth(100);
        tabela.setShowGrid(true);
        tabela.setBackground(Color.PINK);
        tabela.setForeground(Color.BLACK);

    }

    public final void definirTabelaSimbolos() {
        JTable tabela = this.view.getJTableTabelaSimbolos();

        this.tabelaDeSimbolos = new DefaultTableModel(new Object[]{"linha", "ID", "Lexema", "Token"}, 0) {
            @Override
            public boolean isCellEditable(int rowIndex, int mColIndex) {
                return false;
            }
        };
        tabelaDeSimbolos.setNumRows(0);
        tabela.setModel(tabelaDeSimbolos);
        TableColumnModel columnModel = tabela.getColumnModel();
        JTableRenderer renderer = new JTableRenderer();
        renderer.setHorizontalAlignment(SwingConstants.CENTER);
        columnModel.getColumn(0).setCellRenderer(renderer);

        tabela.getColumnModel().getColumn(0).setMaxWidth(35);
        tabela.getColumnModel().getColumn(1).setPreferredWidth(35);
        tabela.getColumnModel().getColumn(2).setPreferredWidth(100);
        tabela.getColumnModel().getColumn(3).setPreferredWidth(205);
        tabela.setSelectionMode(0);
        tabela.setShowGrid(true);
        tabela.setBackground(new Color(153, 204, 255));
        tabela.setForeground(Color.BLACK);
    }

    public class JTableRenderer extends DefaultTableCellRenderer {

        @Override
        protected void setValue(Object value) {
            if (value instanceof ImageIcon) {
                ImageIcon d = (ImageIcon) value;
                setText("");
                setIcon(d);
            } else {
                super.setValue(value);
            }
        }
    }

    public static TelaPrincipalView getViewStatic() {
        return viewStatic;
    }

}
